package com.lanqiao.attendance.service.impl;

import com.lanqiao.attendance.mapper.AdminMapper;
import com.lanqiao.attendance.mapper.StudentMapper;
import com.lanqiao.attendance.mapper.TeacherMapper;
import com.lanqiao.attendance.pojo.Administrator;
import com.lanqiao.attendance.pojo.Student;
import com.lanqiao.attendance.pojo.Teacher;
import com.lanqiao.attendance.service.UserService;
import com.lanqiao.attendance.utils.JWTUtils;
import com.lanqiao.attendance.vo.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: attendance
 * @description
 * @author: 刘 华
 * @create: 2022-07-08 18:48
 **/

@Service
@SuppressWarnings("all")
public class UserServiceImpl implements UserService {

    @Autowired
    StudentMapper studentMapper;  //role = 学生
    @Autowired
    TeacherMapper teacherMapper;  //role = 老师
    @Autowired
    AdminMapper adminMapper;  //role = 管理员


    @Override
    public Result login(LoginParam loginParam) {
        /**
         * 1、获取登录用户信息。如果为空直接返回，这里前台也可以设置。
         * 2、根据角色信息调用不同Mapper进行SQL查询。
         * 3、根据account+password查询登录信息的用户是否存在？
         * 4、存在---------返回成功-根据account生成token。返回前台
         * 5、不存在-------返回失败-账号密码错误信息
         * 6、采用map 返回两个东西。一个token 一个user对象
         */
        String role = loginParam.getRole();
        String account = loginParam.getAccount();
        String password = loginParam.getPassword();
        password = DigestUtils.md5Hex(password + "shzu");
//       生成返回数据结构
        List<Object> resultList = new ArrayList<>();



        //用户名和密码判空
        if ( StringUtils.isBlank(account)
                || StringUtils.isBlank(password)) {
            return Result.fail(ErrorCode.PARAMS_NOTNULL.getCode(), ErrorCode.PARAMS_NOTNULL.getMsg());
        }
        if(StringUtils.isBlank(role+"")){
            return Result.fail(ErrorCode.PARAMS_NOTNULL.getCode(),"请选择角色后再登录" );
        }
        if (role.equals("学生")) {
            Student student = studentMapper.queryByAccountAndPwd(account, password);

            if (student == null) {
                return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
            } else {
                String token = JWTUtils.createToken(student.getId(), "学生");
                resultList.add(token);
                resultList.add(student);
                return Result.success("登录成功", resultList);
            }
        } else if (role.equals("老师")) {
            Teacher teacher = teacherMapper.queryByAccountAndPwd(account, password);
            if (teacher == null) {
                return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
            } else {
                String token = JWTUtils.createToken(teacher.getId(),"老师");
                resultList.add(token);
                resultList.add(teacher);
                return Result.success("登录成功", resultList);
            }
        } else {
            Administrator admin = adminMapper.queryByAccountAndPwd(account, password);
            System.out.println(admin);
            if (admin == null) {
                return Result.fail(ErrorCode.ACCOUNT_PWD_NOT_EXIST.getCode(), ErrorCode.ACCOUNT_PWD_NOT_EXIST.getMsg());
            } else {
                String token = JWTUtils.createToken(admin.getId(), "管理员");
                resultList.add(token);
                resultList.add(admin);
                return Result.success("登录成功", resultList);
            }
        }

    }


    /**
     * 验证token 由于代理主键不同表存在冲突，这里获取登录用户的id和角色
     * 确定唯一性。
     *
     * @param token
     * @return
     */

    @Override
    public Object checkToken(String token) {
        if (StringUtils.isBlank(token)) {
            return null;
        }
//        解析token，获取解析结果map，然后从map获取用户id，然后通过sql获取用户
        System.out.println(token);
        Map<String, Object> stringObjectMap = JWTUtils.checkToken(token);
        if (stringObjectMap == null) {
            return null;
        }
//        然后从map获取用户id和角色id。然后通过sql获取用户
        Long id = Long.parseLong(stringObjectMap.get("id").toString());
        String role = stringObjectMap.get("role")+"";
        if (role.equals("学生")) {
//         return studentMapper.queryById(id);
            return new Student();
        } else if (role.equals("老师")) {
//         return teacherMapper.queryById(id);
            return new Teacher();
        } else {
//         return adminMapper.queryById(id);
            return new Administrator();
        }

    }

    @Override
    public Result register(RegisterParam registerParam) {
        String role = registerParam.getRole();
        String account = registerParam.getAccount();
        if (role.equals("学生")) {
            Student student = studentMapper.queryStuByAccount(account);
            if (student != null) {
                return Result.fail(444, "学生账户已存在");
            }
            Student student1 = new Student();
            student1.setAccount(registerParam.getAccount());
            //            加密
            student1.setPassword(DigestUtils.md5Hex(registerParam.getPassword() + "shzu"));
            student1.setEmail(registerParam.getEmail());
            student1.setName(registerParam.getName());
            student1.setTelephone(registerParam.getPhone());
            student1.setEmail(registerParam.getEmail());
            int i = studentMapper.insertStudent(student1);
            return Result.success("注册成功", null);
        } else if (role.equals("老师")) {
            Teacher teacher = teacherMapper.queryTeacherByNum(account);
            if (teacher != null) {
                return Result.fail(444, "教师账户已存在");
            }
            Teacher teacher1 = new Teacher();
            teacher1.setAccount(registerParam.getAccount());
//            teacher       加密
            teacher1.setPassword(DigestUtils.md5Hex(registerParam.getPassword() + "shzu"));
            teacher1.setEmail(registerParam.getEmail());
            teacher1.setName(registerParam.getName());
            teacher1.setPhone(registerParam.getPhone());
            teacher1.setEmail(registerParam.getEmail());
          int i = teacherMapper.addTeacher(new TeacherVo(teacher1));
            return Result.success("注册成功", null);
        } else {
            Administrator administrator = adminMapper.queryByAccount(account);
            if (administrator != null) {
                return Result.fail(444, "管理员账户已存在");
            }
            Administrator administrator1 = new Administrator();
            administrator1.setAdmUsername(registerParam.getAccount());
//          administratorer       加密
            administrator1.setAdmPassword(DigestUtils.md5Hex(registerParam.getPassword() + "shzu"));
            administrator1.setAdmEmail(registerParam.getEmail());

            administrator1.setAdmTelephone(registerParam.getPhone());
            administrator1.setAdmEmail(registerParam.getEmail());
            int i = adminMapper.register(administrator1);
            return Result.success("注册成功", null);


        }

    }


}
